import React, { useState } from 'react';
import { WechatOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

interface FormState {
  username: string;
  password: string;
  confirmPassword?: string;
}

interface Errors {
  username?: string;
  password?: string;
  confirmPassword?: string;
  general?: string;
}

const RegisterLoginForm: React.FC = () => {
  const [mode, setMode] = useState<'login' | 'register'>('login');
  const [form, setForm] = useState<FormState>({ username: '', password: '', confirmPassword: '' });
  const [errors, setErrors] = useState<Errors>({});
  const [submitted, setSubmitted] = useState(false);
  const navigate = useNavigate();

  const validate = (): Errors => {
    const errs: Errors = {};
    if (!form.username) errs.username = '用户名不能为空';
    if (!form.password) errs.password = '密码不能为空';
    else if (form.password.length < 6 || form.password.length > 20) errs.password = '密码需6-20位';
    else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/.test(form.password)) errs.password = '密码需包含字母和数字，且不能有空格和特殊字符';
    if (mode === 'register') {
      if (!form.confirmPassword) errs.confirmPassword = '请确认密码';
      else if (form.password !== form.confirmPassword) errs.confirmPassword = '两次密码不一致';
    }
    return errs;
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm({ ...form, [e.target.name]: e.target.value });
    setErrors({ ...errors, [e.target.name]: undefined });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const validationErrors = validate();
    setErrors(validationErrors);
    setSubmitted(true);
    if (Object.keys(validationErrors).length === 0) {
      try {
        const url =
          mode === 'login'
            ? 'http://localhost:3000/login'
            : 'http://localhost:3000/register';
        const res = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            username: form.username,
            password: form.password,
          }),
        });
        const data = await res.json();
        if (!res.ok) {
          setErrors({ general: data.msg || '请求失败' });
        } else {
          if (mode === 'register') {
            alert(data.msg || '注册成功');
            setMode('login'); // 注册成功后切换到登录
            setErrors({});
          } else {
            alert(data.msg || '登录成功');
            navigate('/layout/shouye'); // 登录成功后跳转到首页
          }
          setForm({ username: '', password: '', confirmPassword: '' });
          setSubmitted(false);
        }
      } catch (err) {
        setErrors({ general: '网络错误' });
      }
    }
  };

  return (
    <div
      style={{
        // width: 430,
        height: 932,
        margin: '0 auto',
        marginTop: 24,
        border: '1px solid #eee',
        borderRadius: 24,
        boxShadow: '0 4px 24px rgba(0,0,0,0.08)',
        background: '#fff',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        boxSizing: 'border-box',
        padding: 32,
      }}
    >
      <h2 style={{ fontSize: 28, fontWeight: 700, marginBottom: 32 }}>{mode === 'login' ? '登录' : '注册'}</h2>
      <form onSubmit={handleSubmit} style={{ width: '100%' }}>
        {errors.general && (
          <div style={{ color: 'red', marginBottom: 12 }}>{errors.general}</div>
        )}
        <div style={{ marginBottom: 24 }}>
          <input
            name="username"
            placeholder="用户名"
            value={form.username}
            onChange={handleChange}
            style={{
              width: '100%',
              padding: '16px 14px',
              fontSize: 18,
              borderRadius: 12,
              border: '1px solid #ddd',
              outline: 'none',
              boxSizing: 'border-box',
            }}
          />
          {errors.username && <div style={{ color: 'red', fontSize: 14, marginTop: 4 }}>{errors.username}</div>}
        </div>
        <div style={{ marginBottom: 24 }}>
          <input
            name="password"
            type="password"
            placeholder="密码"
            value={form.password}
            onChange={handleChange}
            style={{
              width: '100%',
              padding: '16px 14px',
              fontSize: 18,
              borderRadius: 12,
              border: '1px solid #ddd',
              outline: 'none',
              boxSizing: 'border-box',
            }}
          />
          {errors.password && <div style={{ color: 'red', fontSize: 14, marginTop: 4 }}>{errors.password}</div>}
        </div>
        {mode === 'register' && (
          <div style={{ marginBottom: 24 }}>
            <input
              name="confirmPassword"
              type="password"
              placeholder="确认密码"
              value={form.confirmPassword}
              onChange={handleChange}
              style={{
                width: '100%',
                padding: '16px 14px',
                fontSize: 18,
                borderRadius: 12,
                border: '1px solid #ddd',
                outline: 'none',
                boxSizing: 'border-box',
              }}
            />
            {errors.confirmPassword && <div style={{ color: 'red', fontSize: 14, marginTop: 4 }}>{errors.confirmPassword}</div>}
          </div>
        )}
        <button
          type="submit"
          style={{
            width: '100%',
            padding: '16px 0',
            fontSize: 20,
            borderRadius: 16,
            border: 'none',
            background: '#007bff',
            color: '#fff',
            fontWeight: 600,
            marginBottom: 16,
            cursor: 'pointer',
            boxShadow: '0 2px 8px rgba(0,123,255,0.08)',
            transition: 'background 0.2s',
          }}
        >
          {mode === 'login' ? '登录' : '注册'}
        </button>
      </form>
      <div style={{ textAlign: 'center', fontSize: 16, marginTop: 8 }}>
        {mode === 'login' ? (
          <span>
            没有账号？{' '}
            <a href="#" onClick={() => { setMode('register'); setErrors({}); setSubmitted(false); }} style={{ color: '#007bff', textDecoration: 'none', fontWeight: 500 }}>
              去注册
            </a>
          </span>
        ) : (
          <span>
            已有账号？{' '}
            <a href="#" onClick={() => { setMode('login'); setErrors({}); setSubmitted(false); }} style={{ color: '#007bff', textDecoration: 'none', fontWeight: 500 }}>
              去登录
            </a>
          </span>
        )}
      </div>
      {/* 绿色微信图标 */}
      <h2>点击微信图标进入小程序</h2>
      <div style={{ width: '100%', display: 'flex', justifyContent: 'center', marginTop: 32 }}>
        <WechatOutlined style={{ fontSize: 48, color: '#1AAD19' }} onClick={()=>{navigate('/layout/xiang')}}/>
      </div>
    </div>
  );
};

export default RegisterLoginForm;
